<?php
namespace app\api\controller;

require_once VENDOR_PATH . "Wxpay/lib/WxPay.Api.php"; // 前面增加VENDOR_PATH，是因为找不到文件路径
require_once VENDOR_PATH . 'Wxpay/lib/WxPay.Notify.php';
require_once VENDOR_PATH . 'Wxpay/lib/log.php';

//初始化日志
$logHandler = new \CLogFileHandler(VENDOR_PATH . "Wxpay/logs/" . date('Y-m-d') . '.log');
$log = \Log::Init($logHandler, 15);

/**
 * 微信支付 - 回调处理
 *
 * @author Yangpan
 */
class WxNotify extends \WxPayNotify
{
    //查询订单
    public function Queryorder($transaction_id)
    {
        $input = new \WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        $result = \WxPayApi::orderQuery($input);
        if (array_key_exists("return_code", $result) && array_key_exists("result_code", $result) && $result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS") {
            return true;
        }
        return false;
    }
    
    // 注意 $data['debug'] 存在，打开调试模式
    // 重写回调处理函数
    public function NotifyProcess($data, &$msg)
    {

        db('order')->where(['id'=>4667])->update(['status'=>10]);


        # 写入日志文件
        \Log::INFO("call back:" . json_encode($data));
        $notfiyOutput = array();
        
        logWriteInFile('notify1', $data);

        if ( ! array_key_exists("transaction_id", $data)) {
            $msg = "输入参数不正确";
            return false;
        }
        
        # 查询订单，判断订单真实性 - 调试时不验证
        if ( ! isset($data['debug'])) {
            if ( ! $this->Queryorder($data["transaction_id"])) {
                $msg = "订单查询失败";
                return false;
            }
        }
        
        # 付款失败
        if ($data['result_code'] != 'SUCCESS') {
            db('order')->where(['out_trade_no'=>$data['out_trade_no']])->update(['status'=>3]);
            return false;
        }
        
        // 查询订单表
        $orderMsg = db('order')->where(['out_trade_no'=>$data['out_trade_no']])->find();
        
        if ( ! $orderMsg) {
            $msg = '订单号错误';
            return false;
        }
        
        # 金额单位为分
        if ($orderMsg['amount'] * 100 != $data['total_fee']) {
            $msg = '金额错误';
            return false;
        }
        
        if (strlen($orderMsg['transaction_id']) > 0) {
            $msg = '订单已经处理';
            return false;
        }
        
        $param = json_decode($orderMsg['param'], true);
        
        # 处理单商户
        if ($param['type'] == 'single_store') {
            $this->oneShopOrder($orderMsg, $data);
        } elseif ($param['type'] == 'multi_store') {
            # 处理多商户
        } elseif ($param['type'] == 'other') {
            # 处理其它...
        } elseif ($param['type'] == 'mingpain_pay') {
			# 处理大学生名片
			
			$updata = [];
			$updata['transaction_id'] = $orderMsg['transaction_id'];
			$updata['status'] = 4;
			$updata['status_confirm'] = 1; // 待发货
			$updata['time_end'] = date('Y-m-d H:i:s');
			
			db('order')->where(['out_trade_no'=>$data['out_trade_no']])->update($updata);
			
            //货品id
			$recharge = db("card_recharge")->where(["id"=>$param['recharge_id']])->find();
				
			//用户
			$user = db("card_card")->where(["user_id"=>$param['user_id']])->find();
				
			$ledou = $user["account"] + $recharge["num"];
			db("card_card")->where(["user_id"=>$param['user_id']])->update(["account"=>$ledou]);
        }
        
        return true;
    }
    
    # 在下面定义业务逻辑方法
    

    /**
     * 处理单商户
     * 
     * @param array $dbOrderData    数据库中查询的订单信息
     * @param array $wxReturn       微信返回的支付回调数据
     */
    private function oneShopOrder($dbOrderData, $wxReturn)
    {        
        // 根据返回结果，处理业务逻辑
        $updata = [];
        $updata['transaction_id'] = $wxReturn['transaction_id'];
        $updata['status'] = 4;
        $updata['status_confirm'] = 1; // 待发货
        $updata['time_end'] = date('Y-m-d H:i:s');
        
        db('order')->where(['out_trade_no'=>$dbOrderData['out_trade_no']])->update($updata);
          
        db('xixiche_order')->where(['order_id'=>$dbOrderData['out_trade_no']])->update(['status'=>1]);      
        // 根据admin_id判断不同商户
        
        // 注意 - 不要在下面写sql等逻辑代码，逻辑代码写到自己项目的控制器中,下面只需要 new
        
        // 洗洗车 - 商品支付
        if ($dbOrderData['admin_id'] == 1001) {
           $orderId = $dbOrderData['out_trade_no'];
           $order = new Xixiche();
           $order->order_status($orderId);
        } elseif ($dbOrderData['admin_id'] == 1002) {
        }
        
        
    }
    
    # 多商户
}